<template>
  <div class="merchant-apply-container">
    <Header />
    
    <div class="main-content">
      <div class="merchant-apply-wrapper">
        <el-card class="apply-card">
          <div slot="header" class="clearfix">
            <span class="card-title">申请成为商家</span>
            <el-button style="float: right; padding: 3px 0;" type="text" @click="goBack">返回用户中心</el-button>
          </div>
          
          <el-alert
            v-if="submitted"
            :title="alertMessage"
            :type="alertType"
            show-icon
            :closable="false">
          </el-alert>
          
          <el-steps :active="active" finish-status="success" align-center style="margin: 30px 0;">
            <el-step title="填写基本信息"></el-step>
            <el-step title="上传证照"></el-step>
            <el-step title="提交审核"></el-step>
          </el-steps>
          
          <div class="step-content">
            <!-- 步骤1：基本信息 -->
            <div v-show="active === 0">
              <el-form ref="basicInfoForm" :model="merchantForm" :rules="basicRules" label-width="100px">
                <el-form-item label="店铺名称" prop="shopName">
                  <el-input v-model="merchantForm.shopName" placeholder="请输入店铺名称"></el-input>
                </el-form-item>
                
                <el-form-item label="店铺介绍" prop="shopDesc">
                  <el-input type="textarea" v-model="merchantForm.shopDesc" rows="4" placeholder="请简要描述店铺特色、经营范围等"></el-input>
                </el-form-item>
                
                <el-form-item label="营业时间" prop="businessHours">
                  <el-input v-model="merchantForm.businessHours" placeholder="例如：10:00-22:00"></el-input>
                </el-form-item>
                
                <el-form-item label="联系人" prop="contactPerson">
                  <el-input v-model="merchantForm.contactPerson" placeholder="请输入联系人姓名"></el-input>
                </el-form-item>
                
                <el-form-item label="联系电话" prop="contactPhone">
                  <el-input v-model="merchantForm.contactPhone" placeholder="请输入联系电话"></el-input>
                </el-form-item>
                
                <el-form-item label="店铺地址" prop="shopAddress">
                  <el-input v-model="merchantForm.shopAddress" placeholder="请输入店铺详细地址"></el-input>
                </el-form-item>
                
                <el-form-item label="店铺LOGO">
                  <el-upload
                    class="avatar-uploader"
                    :action="`${$baseURL}/api/upload/common`"
                    :show-file-list="false"
                    :on-success="handleLogoSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="merchantForm.shopLogo" :src="merchantForm.shopLogo" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                  <div class="upload-tip">建议尺寸200x200像素，JPG/PNG格式</div>
                </el-form-item>
              </el-form>
              
              <div class="step-action">
                <el-button type="primary" @click="nextStep">下一步</el-button>
              </div>
            </div>
            
            <!-- 步骤2：证照上传 -->
            <div v-show="active === 1">
              <el-form ref="licenseForm" :model="merchantForm" :rules="licenseRules" label-width="150px">
                <el-form-item label="营业执照" prop="businessLicense">
                  <el-upload
                    class="license-uploader"
                    :action="`${$baseURL}/api/upload/common`"
                    :show-file-list="false"
                    :on-success="handleBusinessLicenseSuccess"
                    :before-upload="beforeLicenseUpload">
                    <img v-if="merchantForm.businessLicense" :src="merchantForm.businessLicense" class="license">
                    <div v-else class="upload-placeholder">
                      <i class="el-icon-plus"></i>
                      <div>点击上传营业执照</div>
                    </div>
                  </el-upload>
                  <div class="upload-tip">请上传清晰完整的营业执照照片或扫描件</div>
                </el-form-item>
                
                <el-form-item label="食品经营许可证" prop="foodLicense">
                  <el-upload
                    class="license-uploader"
                    :action="`${$baseURL}/api/upload/common`"
                    :show-file-list="false"
                    :on-success="handleFoodLicenseSuccess"
                    :before-upload="beforeLicenseUpload">
                    <img v-if="merchantForm.foodLicense" :src="merchantForm.foodLicense" class="license">
                    <div v-else class="upload-placeholder">
                      <i class="el-icon-plus"></i>
                      <div>点击上传食品经营许可证</div>
                    </div>
                  </el-upload>
                  <div class="upload-tip">请上传清晰完整的食品经营许可证照片或扫描件</div>
                </el-form-item>
              </el-form>
              
              <div class="step-action">
                <el-button @click="prevStep">上一步</el-button>
                <el-button type="primary" @click="nextStep">下一步</el-button>
              </div>
            </div>
            
            <!-- 步骤3：提交审核 -->
            <div v-show="active === 2">
              <div class="submit-info">
                <h3>申请信息确认</h3>
                
                <el-descriptions :column="1" border>
                  <el-descriptions-item label="店铺名称">{{ merchantForm.shopName }}</el-descriptions-item>
                  <el-descriptions-item label="店铺介绍">{{ merchantForm.shopDesc }}</el-descriptions-item>
                  <el-descriptions-item label="营业时间">{{ merchantForm.businessHours }}</el-descriptions-item>
                  <el-descriptions-item label="联系人">{{ merchantForm.contactPerson }}</el-descriptions-item>
                  <el-descriptions-item label="联系电话">{{ merchantForm.contactPhone }}</el-descriptions-item>
                  <el-descriptions-item label="店铺地址">{{ merchantForm.shopAddress }}</el-descriptions-item>
                </el-descriptions>
                
                <div class="image-preview-container">
                  <div class="image-preview">
                    <div class="preview-label">店铺LOGO</div>
                    <img v-if="merchantForm.shopLogo" :src="merchantForm.shopLogo" class="preview-image">
                  </div>
                  
                  <div class="image-preview">
                    <div class="preview-label">营业执照</div>
                    <img v-if="merchantForm.businessLicense" :src="merchantForm.businessLicense" class="preview-image">
                  </div>
                  
                  <div class="image-preview">
                    <div class="preview-label">食品经营许可证</div>
                    <img v-if="merchantForm.foodLicense" :src="merchantForm.foodLicense" class="preview-image">
                  </div>
                </div>
                
                <div class="declaration">
                  <el-checkbox v-model="declaration">我承诺以上提交的信息真实有效，如有虚假信息愿意承担相应后果</el-checkbox>
                </div>
              </div>
              
              <div class="step-action">
                <el-button @click="prevStep">上一步</el-button>
                <el-button type="primary" @click="submitApplication" :loading="submitting" :disabled="!declaration">提交申请</el-button>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
    
    <Footer />
  </div>
</template>

<script>
import Header from '@/components/Header'
import Footer from '@/components/Footer'
import { applyMerchant, checkMerchantExists } from '@/api/merchant'

export default {
  name: 'MerchantApply',
  components: {
    Header,
    Footer
  },
  data() {
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入联系电话'))
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    
    return {
      // 步骤
      active: 0,
      // 商家表单
      merchantForm: {
        userId: null,
        shopName: '',
        shopLogo: '',
        shopDesc: '',
        businessHours: '',
        contactPerson: '',
        contactPhone: '',
        shopAddress: '',
        businessLicense: '',
        foodLicense: '',
        status: 0, // 默认为待审核
        businessStatus: 0 // 默认为休息中
      },
      // 基本信息验证规则
      basicRules: {
        shopName: [
          { required: true, message: '请输入店铺名称', trigger: 'blur' },
          { min: 2, max: 30, message: '长度在2到30个字符之间', trigger: 'blur' }
        ],
        shopDesc: [
          { required: true, message: '请输入店铺介绍', trigger: 'blur' }
        ],
        businessHours: [
          { required: true, message: '请输入营业时间', trigger: 'blur' }
        ],
        contactPerson: [
          { required: true, message: '请输入联系人姓名', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        shopAddress: [
          { required: true, message: '请输入店铺地址', trigger: 'blur' }
        ]
      },
      // 证照验证规则
      licenseRules: {
        businessLicense: [
          { required: true, message: '请上传营业执照', trigger: 'change' }
        ],
        foodLicense: [
          { required: true, message: '请上传食品经营许可证', trigger: 'change' }
        ]
      },
      // 是否确认申报
      declaration: false,
      // 提交状态
      submitting: false,
      submitted: false,
      alertType: 'info',
      alertMessage: ''
    }
  },
  created() {
    // 获取当前用户ID
    const userInfo = JSON.parse(sessionStorage.getItem('user') || '{}')
    if (userInfo && userInfo.id) {
      this.merchantForm.userId = userInfo.id
      
      // 检查用户是否已申请过商家
      this.checkUserMerchant(userInfo.id)
    } else {
      this.$message.error('获取用户信息失败，请先登录')
      this.$router.push('/login')
    }
  },
  methods: {
    // 检查用户是否已申请商家
    checkUserMerchant(userId) {
      checkMerchantExists(userId).then(response => {
        if (response.code === 200 && response.data === true) {
          this.submitted = true
          this.alertType = 'warning'
          this.alertMessage = '您已提交过商家申请，请勿重复申请'
        }
      }).catch(error => {
        console.error('检查商家申请失败', error)
      })
    },
    
    // 上一步
    prevStep() {
      if (this.active > 0) {
        this.active--
      }
    },
    
    // 下一步
    nextStep() {
      if (this.active === 0) {
        // 验证基本信息
        this.$refs.basicInfoForm.validate(valid => {
          if (valid) {
            if (!this.merchantForm.shopLogo) {
              this.$message.warning('请上传店铺LOGO')
              return
            }
            this.active++
          }
        })
      } else if (this.active === 1) {
        // 验证证照信息
        this.$refs.licenseForm.validate(valid => {
          if (valid) {
            this.active++
          }
        })
      }
    },
    
    // 提交申请
    submitApplication() {
      if (!this.declaration) {
        this.$message.warning('请勾选信息真实性承诺')
        return
      }
      
      this.submitting = true
      
      applyMerchant(this.merchantForm).then(response => {
        if (response.code === 200) {
          this.submitted = true
          this.alertType = 'success'
          this.alertMessage = '申请提交成功，请等待审核'
          
          // 3秒后跳转到用户中心
          setTimeout(() => {
            this.$router.push('/user/info')
          }, 3000)
        } else {
          this.$message.error(response.message || '申请提交失败')
        }
      }).catch(error => {
        console.error('申请提交失败', error)
        this.$message.error('申请提交失败，请稍后重试')
      }).finally(() => {
        this.submitting = false
      })
    },
    
    // 处理LOGO上传成功
    handleLogoSuccess(response) {
      if (response.code === 200) {
        this.merchantForm.shopLogo = response.data.fileUrl
      } else {
        this.$message.error(response.message || 'LOGO上传失败')
      }
    },
    
    // 处理营业执照上传成功
    handleBusinessLicenseSuccess(response) {
      if (response.code === 200) {
        this.merchantForm.businessLicense = response.data.fileUrl
      } else {
        this.$message.error(response.message || '营业执照上传失败')
      }
    },
    
    // 处理食品经营许可证上传成功
    handleFoodLicenseSuccess(response) {
      if (response.code === 200) {
        this.merchantForm.foodLicense = response.data.fileUrl
      } else {
        this.$message.error(response.message || '食品经营许可证上传失败')
      }
    },
    
    // 上传头像前检查
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是JPG或PNG格式!')
      }
      
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过2MB!')
      }
      
      return (isJPG || isPNG) && isLt2M
    },
    
    // 上传证照前检查
    beforeLicenseUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isPDF = file.type === 'application/pdf'
      const isLt5M = file.size / 1024 / 1024 < 5
      
      if (!isImage && !isPDF) {
        this.$message.error('上传证照只能是图片或PDF格式!')
      }
      
      if (!isLt5M) {
        this.$message.error('上传证照大小不能超过5MB!')
      }
      
      return (isImage || isPDF) && isLt5M
    },
    
    // 返回用户中心
    goBack() {
      this.$router.push('/user/info')
    }
  }
}
</script>

<style scoped>
.merchant-apply-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.main-content {
  flex: 1;
  padding: 30px 0;
}

.merchant-apply-wrapper {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 20px;
}

.apply-card {
  border-radius: 8px;
  margin-bottom: 30px;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
}

.step-content {
  padding: 20px 0;
}

.step-action {
  text-align: center;
  margin-top: 30px;
}

.avatar-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.license-uploader {
  width: 300px;
  height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
  cursor: pointer;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.license-uploader:hover {
  border-color: #409EFF;
}

.license {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #8c939d;
}

.upload-placeholder i {
  font-size: 28px;
  margin-bottom: 10px;
}

.submit-info {
  padding: 20px 0;
}

.image-preview-container {
  display: flex;
  justify-content: space-between;
  margin: 30px 0;
  flex-wrap: wrap;
}

.image-preview {
  width: 30%;
  text-align: center;
  margin-bottom: 20px;
}

.preview-label {
  margin-bottom: 10px;
  font-weight: bold;
}

.preview-image {
  width: 100%;
  max-height: 150px;
  object-fit: contain;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}

.declaration {
  margin: 20px 0;
}
</style> 